package com.salary.utils.reader;

import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AssessmentScoreReader extends DataReader<Map<String, Double>>{

    private static final Logger logger = LoggerFactory.getLogger(AssessmentScoreReader.class);

    /**
     * 从考核得分表读取考核得分数据
     *
     * @param assessmentScoreFilePath 考核得分表文件路径
     * @return 姓名到考核得分的映射
     */
    @Override
    public Map<String, Double> readData(String assessmentScoreFilePath) {
        Map<String, Double> scoreData = new HashMap<>();

        try (FileInputStream fis = new FileInputStream(assessmentScoreFilePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("考核得分表中未找到工作表");
                return scoreData;
            }

            logger.info("从考核得分表的'" + sheet.getSheetName() + "'工作表读取数据");

            // 使用通用方法查找列
            Map<String, Integer> columnIndices = findColumnIndices(sheet, new String[]{"姓名", "分数"});

            // 验证是否找到必要的列
            if (!columnIndices.containsKey("姓名") || !columnIndices.containsKey("分数")) {
                logger.error("考核得分表中未找到必要的列");
                return scoreData;
            }

            int nameColIndex = columnIndices.get("姓名");
            int scoreColIndex = columnIndices.get("分数");

            // 从第二行开始读取数据（跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Cell nameCell = row.getCell(nameColIndex);
                if (nameCell == null) continue;

                String name = getCellValueAsString(nameCell).trim();
                if (name.isEmpty()) continue;

                Cell scoreCell = row.getCell(scoreColIndex);
                if (scoreCell == null) continue;

                double score = getCellValueAsDouble(scoreCell);

                // 如果分数为0，则尝试直接读取单元格的字符串值并转换
                if (score == 0) {
                    try {
                        String scoreStr = getCellValueAsString(scoreCell).trim();
                        if (!scoreStr.isEmpty()) {
                            // 移除可能的非数字字符
                            scoreStr = scoreStr.replaceAll("[^0-9.]", "");
                            score = Double.parseDouble(scoreStr);
                        }
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }

                if (score > 0) {
                    scoreData.put(name, score);
                    logger.info("读取到考核得分数据: " + name + " - " + score);
                }
            }

            logger.info("成功从考核得分表读取了 " + scoreData.size() + " 条记录");

        } catch (IOException e) {
            logger.error("读取考核得分表文件失败: " + e.getMessage(), e);
        }

        return scoreData;
    }
}
